//
//  RegisterQueryController.m
//  DYLYJ
//
//  Created by JM on 15/11/21.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "RegisterQueryController2.h"
#import "DYRequestAll.h"
#import "AppDelegate.h"
#import "DYUIKit.h"
#import <TYAttributedLabel.h>

#import "ChangePwdByPhoneController.h"
#import "ChangePwdByPhoneQueryController.h"
#import "RegisterSecurityCodeVC2.h"
@interface RegisterQueryController2 ()
@property(nonatomic,strong)IBOutlet UITextField *phoneCodeTextFeild;

@property(nonatomic,strong)IBOutlet UITextField *phoneTextFeild;
@property(nonatomic,strong)NSMutableAttributedString *string;
@property(nonatomic,strong)UIButton *button;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)NSUInteger timeCount;

@property (weak, nonatomic) IBOutlet TYAttributedLabel *timeButtonLabel;//
@end

@implementation RegisterQueryController2

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.phoneTextFeild.text= self.name;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    RegitsterSendSMSRequest *request = [RegitsterSendSMSRequest request];
    request.DY_captchaId = self.rsponseGetSMSImage.DY_captchaId;
    request.DY_token = self.rsponseGetSMSImage.DY_token;
    request.DY_phone = self.name;
    request.DY_captchaCode = self.code;
    [request requstWithCompletionHandler:^(DYResponse *rs, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    
    self.timeButtonLabel.backgroundColor = [UIColor clearColor];
    
    [self startWaiting:nil];

}

- (IBAction)clickQueryBtn:(id)sender {
  
    [self.view endEditing:YES];
    if ([self.navigationController findvcOfClass:[ChangePwdByPhoneController class]]){//从忘记密码过来
        ChangePwdByPhoneQueryController *vc = [[ChangePwdByPhoneQueryController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    else if (myAppDelegate.islogin){
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        ChangePhoneRequest * request = [ChangePhoneRequest request];
        request.DY_token = myAppDelegate.token;
        request.DY_phone = self.name;
        request.DY_code = self.phoneCodeTextFeild.text;
        [request requstWithCompletionHandler:^(DYResponse *rs, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (error) {
                [MJAlertView showMessage:error.localizedDescription];
                return ;
            }
            [MJAlertView showAlertViewWithTitle:@"提示" message:@"修改手机号成功" clickedButtonBlock:^(NSInteger index) {
                 [self.navigationController popToRootViewControllerAnimated:YES];
            } cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
        }];
    } else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        RegitsterPhoneRequest * request = [RegitsterPhoneRequest request];
        request.DY_phone = self.name;
        request.DY_password = self.pwd;
        request.DY_code = self.phoneCodeTextFeild.text;
        [request requstWithCompletionHandler:^(DYResponse *rs, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (error) {
                [MJAlertView showMessage:error.localizedDescription];
                return ;
            }
            RegitsterPhoneResponse *response = (RegitsterPhoneResponse *)rs;
            myAppDelegate.uid = response.DY_uid;
            myAppDelegate.token = response.DY_token;
            myAppDelegate.islogin = YES;
            myAppDelegate.isDemo = NO;
            [DYSettingTool setObject:request.DY_phone forKey:DYLoginName];
            [DYSettingTool setObject:request.DY_password forKey:DYLoginPwd];
            
            [self.navigationController dismissViewControllerAnimated:YES completion:^{
            }];
            
        }];
    }
  
}
#pragma mark - 定时计数

-(void)clickReSend:(id)sender {
    RegisterSecurityCodeVC2 *vc = [self.navigationController findvcOfClass:[RegisterSecurityCodeVC2 class]];
    [self.navigationController popToViewController:vc animated:YES];
}

- (void)endWaiting
{
    self.timeButtonLabel.exclusiveTouch = YES;
    //
    self.timeButtonLabel.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"没有收到验证码？"];
    self.string = attributedString;
    [attributedString addAttributeTextColor:UIColorFromHexStr(@"#A6937C")];
    [attributedString addAttributeFont:[UIFont systemFontOfSize:15]];
    [self.timeButtonLabel setAttributedText:attributedString];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button = button;
    button.exclusiveTouch = YES;
    [button setTitle:@"重新发送" forState:UIControlStateNormal];
    button.tintColor = UIColorFromHexStr(@"#f39700");
    [button addTarget:self action:@selector(clickReSend:) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 60, 15);
    [self.timeButtonLabel appendView:button];
    [self.timeButtonLabel sizeToFit];
}


- (void)reloadTimeButtonLabelData {
    NSString * timeCountString =  [NSString stringWithFormat:@"      %lus",(unsigned long)self.timeCount];
    NSMutableAttributedString *string1 = [[NSMutableAttributedString alloc]initWithString:timeCountString];
    [string1 addAttributeTextColor:UIColorFromHexStr(@"#f39700")];
    [string1 addAttributeFont:[UIFont systemFontOfSize:15]];
    NSMutableAttributedString *string2 = [[NSMutableAttributedString alloc]initWithString:@"后才可以重发"];
    [string2 addAttributeTextColor:UIColorFromHexStr(@"#A6937C")];
    [string2 addAttributeFont:[UIFont systemFontOfSize:15]];
    
    NSMutableAttributedString *totalString = [[NSMutableAttributedString alloc] initWithAttributedString:string1];
    [totalString appendAttributedString:string2];
    //    [self.timeButtonLabel.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //    [self.timeButtonLabel.textContainer setText:@""];
    [self.timeButtonLabel setAttributedText:totalString];
    //    self.timeButtonLabel.textAlignment = kCTTextAlignmentCenter;//有bug NSTextAlignmentCenter 与 NSTextAlignmentRight反了
    [self.timeButtonLabel sizeToFit];
}

- (void)startWaiting:(id) sender{
    
    self.timeCount =  60;//60秒倒计时
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRepeat) userInfo:nil repeats:YES];
    
    [self reloadTimeButtonLabelData];
}



- (void)timerRepeat {
    self.timeCount --;
    if(self.timeCount == 0) {
        [self.timer invalidate];
        [self endWaiting];
    } else {
        [self reloadTimeButtonLabelData];
    }
}

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}

@end
